#!/bin/bash
echo "🔧 编译独立版本的 cbp2make_ai..."

# 清理
rm -rf bin .objs
mkdir -p bin .objs

# 设置编译参数
INCLUDES="-I./lib -I./lib/tinyxml -I./src"
CXXFLAGS="-Wall -std=c++11 -m64 -DAICODER_ENHANCED -O2"

echo "📦 编译所有必要的文件..."
# 编译lib目录下的文件
g++ $INCLUDES $CXXFLAGS -c lib/stlconfig.cpp -o .objs/stlconfig.o
g++ $INCLUDES $CXXFLAGS -c lib/stlconvert.cpp -o .objs/stlconvert.o
g++ $INCLUDES $CXXFLAGS -c lib/stlfutils.cpp -o .objs/stlfutils.o
g++ $INCLUDES $CXXFLAGS -c lib/stlgpm.cpp -o .objs/stlgpm.o
g++ $INCLUDES $CXXFLAGS -c lib/stlstrings.cpp -o .objs/stlstrings.o
g++ $INCLUDES $CXXFLAGS -c lib/stlvariables.cpp -o .objs/stlvariables.o
g++ $INCLUDES $CXXFLAGS -c lib/stringhash.cpp -o .objs/stringhash.o

# 编译tinyxml
g++ $INCLUDES $CXXFLAGS -c lib/tinyxml/tinystr.cpp -o .objs/tinystr.o
g++ $INCLUDES $CXXFLAGS -c lib/tinyxml/tinyxml.cpp -o .objs/tinyxml.o
g++ $INCLUDES $CXXFLAGS -c lib/tinyxml/tinyxmlerror.cpp -o .objs/tinyxmlerror.o
g++ $INCLUDES $CXXFLAGS -c lib/tinyxml/tinyxmlparser.cpp -o .objs/tinyxmlparser.o

# 编译src核心文件
g++ $INCLUDES $CXXFLAGS -c src/cbp2make.cpp -o .objs/cbp2make.o
g++ $INCLUDES $CXXFLAGS -c src/cbproject.cpp -o .objs/cbproject.o
g++ $INCLUDES $CXXFLAGS -c src/cbptarget.cpp -o .objs/cbptarget.o
g++ $INCLUDES $CXXFLAGS -c src/cbworkspace.cpp -o .objs/cbworkspace.o
g++ $INCLUDES $CXXFLAGS -c src/cbbuildcfg.cpp -o .objs/cbbuildcfg.o
g++ $INCLUDES $CXXFLAGS -c src/cbbuildmgr.cpp -o .objs/cbbuildmgr.o
g++ $INCLUDES $CXXFLAGS -c src/cbglobalvar.cpp -o .objs/cbglobalvar.o
g++ $INCLUDES $CXXFLAGS -c src/cbhelper.cpp -o .objs/cbhelper.o
g++ $INCLUDES $CXXFLAGS -c src/cbpunit.cpp -o .objs/cbpunit.o
g++ $INCLUDES $CXXFLAGS -c src/depsearch.cpp -o .objs/depsearch.o
g++ $INCLUDES $CXXFLAGS -c src/makefile.cpp -o .objs/makefile.o
g++ $INCLUDES $CXXFLAGS -c src/platforms.cpp -o .objs/platforms.o
g++ $INCLUDES $CXXFLAGS -c src/toolchains.cpp -o .objs/toolchains.o
g++ $INCLUDES $CXXFLAGS -c src/buildtools.cpp -o .objs/buildtools.o

echo "🤖 编译AI文件..."
# 修复 WriteCallback
if [ -f "src/unified_ai_client.cpp" ] && ! grep -q "WriteCallback" src/unified_ai_client.cpp; then
    echo "// WriteCallback for curl" >> src/unified_ai_client.cpp
    cat >> src/unified_ai_client.cpp << 'WRITECALLBACK'
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) {
    size_t totalSize = size * nmemb;
    response->append((char*)contents, totalSize);
    return totalSize;
}
WRITECALLBACK
fi

# 编译AI文件
g++ $INCLUDES $CXXFLAGS -c src/ai_model_config.cpp -o .objs/ai_model_config.o
g++ $INCLUDES $CXXFLAGS -c src/unified_ai_client.cpp -o .objs/unified_ai_client.o
g++ $INCLUDES $CXXFLAGS -c src/aicoder_enhancements.cpp -o .objs/aicoder_enhancements.o

echo "🔗 链接..."
g++ .objs/*.o -m64 -lcurl -o bin/cbp2make_ai.exe

if [ -f "bin/cbp2make_ai.exe" ]; then
    echo "🎉 编译成功: bin/cbp2make_ai.exe"
    echo "📋 测试命令:"
    echo "   ./bin/cbp2make_ai.exe --ai-set-model 0 DS-V3.2exp0922"
    echo "   ./bin/cbp2make_ai.exe --help"
else
    echo "❌ 编译失败"
fi
